import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/device.dart';
import '../models/user.dart';

class DeviceService {
  static const String _baseUrl = 'http://localhost:8080/api';

  // 获取用户的所有设备
  Future<List<Device>> getDevices(User user) async {
    try {
      final response = await http.get(
        Uri.parse('$_baseUrl/devices'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ${user.token}',
        },
      );

      if (response.statusCode == 200) {
        final List<dynamic> data = jsonDecode(response.body);
        return data.map((json) => Device.fromJson(json)).toList();
      } else {
        final Map<String, dynamic> error = jsonDecode(response.body);
        throw Exception(error['message'] ?? '获取设备列表失败');
      }
    } catch (e) {
      throw Exception('获取设备列表失败: ${e.toString()}');
    }
  }

  // 获取单个设备详情
  Future<Device> getDevice(User user, String deviceId) async {
    try {
      final response = await http.get(
        Uri.parse('$_baseUrl/devices/$deviceId'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ${user.token}',
        },
      );

      if (response.statusCode == 200) {
        final Map<String, dynamic> data = jsonDecode(response.body);
        return Device.fromJson(data);
      } else {
        final Map<String, dynamic> error = jsonDecode(response.body);
        throw Exception(error['message'] ?? '获取设备详情失败');
      }
    } catch (e) {
      throw Exception('获取设备详情失败: ${e.toString()}');
    }
  }

  // 添加新设备
  Future<Device> addDevice(User user, Map<String, dynamic> deviceData) async {
    try {
      final response = await http.post(
        Uri.parse('$_baseUrl/devices'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ${user.token}',
        },
        body: jsonEncode(deviceData),
      );

      if (response.statusCode == 201) {
        final Map<String, dynamic> data = jsonDecode(response.body);
        return Device.fromJson(data);
      } else {
        final Map<String, dynamic> error = jsonDecode(response.body);
        throw Exception(error['message'] ?? '添加设备失败');
      }
    } catch (e) {
      throw Exception('添加设备失败: ${e.toString()}');
    }
  }

  // 更新设备状态
  Future<Device> updateDeviceStatus(
    User user,
    String deviceId,
    bool status,
  ) async {
    try {
      final response = await http.patch(
        Uri.parse('$_baseUrl/devices/$deviceId/status'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ${user.token}',
        },
        body: jsonEncode({'status': status}),
      );

      if (response.statusCode == 200) {
        final Map<String, dynamic> data = jsonDecode(response.body);
        return Device.fromJson(data);
      } else {
        final Map<String, dynamic> error = jsonDecode(response.body);
        throw Exception(error['message'] ?? '更新设备状态失败');
      }
    } catch (e) {
      throw Exception('更新设备状态失败: ${e.toString()}');
    }
  }

  // 更新设备属性
  Future<Device> updateDeviceAttributes(
    User user,
    String deviceId,
    Map<String, dynamic> attributes,
  ) async {
    try {
      final response = await http.patch(
        Uri.parse('$_baseUrl/devices/$deviceId/attributes'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ${user.token}',
        },
        body: jsonEncode({'attributes': attributes}),
      );

      if (response.statusCode == 200) {
        final Map<String, dynamic> data = jsonDecode(response.body);
        return Device.fromJson(data);
      } else {
        final Map<String, dynamic> error = jsonDecode(response.body);
        throw Exception(error['message'] ?? '更新设备属性失败');
      }
    } catch (e) {
      throw Exception('更新设备属性失败: ${e.toString()}');
    }
  }

  // 删除设备
  Future<void> deleteDevice(User user, String deviceId) async {
    try {
      final response = await http.delete(
        Uri.parse('$_baseUrl/devices/$deviceId'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ${user.token}',
        },
      );

      if (response.statusCode != 204) {
        final Map<String, dynamic> error = jsonDecode(response.body);
        throw Exception(error['message'] ?? '删除设备失败');
      }
    } catch (e) {
      throw Exception('删除设备失败: ${e.toString()}');
    }
  }
}